package com.m4f.city.web.controller;

import java.io.IOException;
import java.security.Principal;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.cache.CacheException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.oauth2.provider.verification.VerificationCodeAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.m4f.city.business.domain.Application;
import com.m4f.city.business.domain.Company;
import com.m4f.city.business.domain.InternalUser;
import com.m4f.gaeweb.business.service.impl.GaeM4FUserDetailService;
import com.m4f.gaeweb.exception.M4FException;
import com.m4f.gaeweb.web.utils.StackTraceUtil;

@Controller
@RequestMapping(value="/login")
public class LoginController extends BaseController {

	private static final Logger LOGGER = Logger.getLogger(LoginController.class.getName());
	
	public LoginController() throws CacheException {
		super();
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String getView(HttpServletRequest request, HttpServletResponse response, Principal currentUser, Model model,
			@RequestParam(required=false, defaultValue="") String login_error, @RequestHeader(required=false,value="referer") String referer, HttpSession session)
			throws IOException, ClassNotFoundException {
		/*VerificationCodeAuthenticationToken token = (VerificationCodeAuthenticationToken) session.getAttribute("org.springframework.security.oauth2.provider.webserver.DefaultClientAuthenticationCache#SAVED_AUTH");
		if(request.getParameter("client_id") != null && !("").equals(request.getParameter("client_id"))) {
			response.sendRedirect(request.getContextPath()+"/app/loginoauth?client_id="+request.getParameter("client_id"));
		} else if(referer != null && !("").equals(referer) && referer.contains("client_id")) {
			
		}*/
		VerificationCodeAuthenticationToken token = (VerificationCodeAuthenticationToken) session.getAttribute("org.springframework.security.oauth2.provider.webserver.DefaultClientAuthenticationCache#SAVED_AUTH");
		if((token != null && !("").equals(token.getClientId())) ||
			request.getParameter("client_id") != null && !("").equals(request.getParameter("client_id"))) {
			String clientId = request.getParameter("client_id") != null && !("").equals(request.getParameter("client_id")) ? request.getParameter("client_id") : token.getClientId();
			try {
				Application app = this.serviceLocator.getApplicationService().getAppliaction(clientId);
				model.addAttribute("client", app);
				if(app != null) {
					Company company = this.serviceLocator.getCompanyService().getObjectById(app.getCompanyId());
					model.addAttribute("company", company);
				}
			} catch(Exception e) {
				LOGGER.log(Level.SEVERE, StackTraceUtil.getStackTrace(e)); // TODO redirect to oauth page error
				return "login";
			}
			return "oauth.access.loginconfirm";
		}
		return "login";
	}
	
	@RequestMapping(value="/postlogin", method=RequestMethod.GET)
	public String postLogin(HttpServletRequest request, Principal currentUser, Model model,
			@RequestParam(required=false, defaultValue="") String login_error, Locale locale) throws M4FException {
			InternalUser user = getInternalUser(currentUser);
			if(user.getAuthorities() != null) {
				if(user.getAuthorities().contains(new GrantedAuthorityImpl(GaeM4FUserDetailService.ROLE_ROOT))) {
					return "redirect:/" + locale.getLanguage()+ "/admin/home";
				} else if(user.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_USER"))) {
					return "redirect:/" + locale.getLanguage()+ "/user/home";
				}
			}
			return "redirect:/" + locale.getLanguage() + "/";
	}
	
	@RequestMapping(value="/postlogout", method=RequestMethod.GET)
	public String postLogout(HttpServletRequest request, Principal currentUser, Model model,
			@RequestParam(required=false, defaultValue="") String login_error, Locale locale)
			throws IOException, ClassNotFoundException {
		
			
		return "redirect:/"+ locale.getLanguage() + "/";
	}
}